<script setup>
import { reactive, watch, onMounted, onUnmounted } from 'vue';
import { deepCopy } from '@T2/utils/utils.ts';
import { sensorApi } from '@T2/service/api.ts';
import { getBasicUDS } from '@T2/utils/BIM_API.js';
import { MyHomeView, unitViews } from '../constant.ts';
import DeviceEcharts from '../components/deviceEcharts.vue';

const { BIMRat } = defineProps({
  BIMRat: {
    type: Object,
    required: true,
  },
});
const Resd = reactive({
  ready: false,
  action: false,
  basicUDS: [],
  showUnit: null,
});

onMounted(async () => {
  Resd.basicUDS = await getBasicUDS();
  deailwithUDS();
});
let Timer = null;
function deailwithUDS() {
  let sArray = [], id__in = '';
  Resd.basicUDS.forEach(unit => {
    unit.deChildren.forEach(de => {
      if (de.e_sensors.length > 0) {
        sArray.push(...de.e_sensors);
      }
    });
  });
  id__in = sArray.map(i => i.id).toString();
  if (!id__in) {
    return;
  }
  /* 10秒刷新一次sensors数据 */
  refreshSensors();
  if (Timer !== null) {
    clearInterval(Timer);
  }
  Timer = setInterval(() => {
    refreshSensors();
  }, 10000);
  function refreshSensors() {
    /* 直接修改sArray */
    sensorApi({
      method: "get",
      params: {
        page: 1,
        id__in: id__in,
      },
    }).then(res => {
      const { results } = res;
      sArray.forEach(item => {
        const sensor = results.find(i => i.id === item.id);
        const value = +sensor.lastdata_cn;
        if (value || value === 0) {
          item.value = value;
        } else {
          item.value = sensor.lastdata_cn;
        }
        item.name = sensor.name;
        item.datatype = sensor.datatype;
        item.unit = sensor.unit;
        item.timestamp = sensor.timestamp;
      });
      Resd.ready = true;
    })
  }
}
onUnmounted(() => {
  if (Timer !== null) {
    clearInterval(Timer);
  }
});

function handleUnit(unit) {
  Resd.action = true;
  initModelViewer();
  if (unit._selected) {
    unit._opened = !unit._opened;
    unit._selected = false;
    setRightData(null);
    return;
  }
  selectSomeUnit(unit);
  setRightData(unit);
  createUnitCustom(unit);
}
function selectSomeUnit(unit) {
  Resd.basicUDS.forEach(item => {
    item._selected = item.id === unit.id;
    item._opened = item.id === unit.id;
  });
  unit.deChildren.forEach(item => item._selected = false);
}
function listTitleClick() {
  initModelViewer();
  Resd.basicUDS.forEach(item => {
    item._selected = false;
    item._opened = false;
  });
  if (!Resd.action) {
    Resd.basicUDS.forEach(unit => {
      createUnitCustom(unit)
    });
  }
  Resd.action = !Resd.action;
}

function initModelViewer() {
  BIMRat.model3D.restoreDefault();
  BIMRat.drawableContainer.clear();
  BIMRat.viewer3D.setCameraStatus(MyHomeView);
}
function createUnitCustom(unit) {
  let unitView = unitViews[unit.code];
  let config = new Glodon.Bimface.Plugins.Drawable.CustomItemConfig();
  unitView.worldPosition.forEach(worldPosition => {
    let content = document.createElement('div');
    content.innerHTML = `<div class="leadTips jump-4times">
      <div class="tip-box unit-icon">
        <div class="name">${ unitView.name }</div>
        <img src="${require('../assets/device/unitPosition.png')}" width="43" height="52"  />
      </div>
    </div>`;
    config.content = content;
    config.viewer = BIMRat.viewer3D;
    config.worldPosition = worldPosition;
    let customItem = new Glodon.Bimface.Plugins.Drawable.CustomItem(config);
    customItem.onClick(function (e) {
      selectSomeUnit(unit);
      setRightData(null);
      BIMRat.viewer3D.setCameraStatus(unitView.camera);
      getUnitView(unit);
    });
    BIMRat.drawableContainer.addItem(customItem);
  });
}
function getUnitView(unit, simple = false) {
  BIMRat.model3D.restoreDefault();
  BIMRat.drawableContainer.clear();
  let unitView = unitViews[unit.code];
  if (unitView?.hides?.length) {
    BIMRat.model3D.hideComponentsById(unitView.hides);
  }
  if (unitView?.opcts?.length) {
    BIMRat.model3D.overrideComponentsOpacityById(unitView.opcts, unitView.opacity);
  }
  if (unitView?.selecteds?.length) {
    BIMRat.model3D.addSelectedComponentsById(unitView.selecteds);
  }
  unit.deChildren.forEach(de => {
    let position = new Object();
    let { max, min } = BIMRat.model3D.getBoundingBoxById(de.e_elementid);
    position = { "x": (max.x + min.x) * 0.5, "y": (max.y + min.y) * 0.5, "z": (max.z + min.z) * 0.5 };
    const states = de.e_sensors.filter(i => i.datatype === '状态型');
    const values = de.e_sensors.filter(i => i.datatype === '数值型');
    const state = checkStatus(states || []);
    let config = new Glodon.Bimface.Plugins.Drawable.CustomItemConfig();
    let content = document.createElement('div');
    
    let valusStr = '';
    if (values.length) {
      const obj = values[0];
      const text = obj.value === '掉线' ? '- -' : obj.value;
      const danwei = obj.unit ? `<span> ${obj.unit}</span>` : '';
      valusStr = `<div class="value-data">${ text }${ danwei }</div>`;
    }
    let stateStr = '<div class="state"></div>', color = 'red';
    if (['掉线', '故障'].includes(state)) {
      color = 'red';
    } else if (['运行', '开到位', '关到位'].includes(state)) {
      color = 'green';
    } else if (['停止'].includes(state)) {
      color = 'blue';
    } else {
      stateStr = '';
    }
    
    content.innerHTML = `<div class="leadTips" id="tipsDeviceID${ de.id }">
      <div class="tip-box current-value ${color}">
        <div class="device-name">${ de.name }</div>
        ${ stateStr || valusStr }
      </div>
    </div>`;
    // if (simple) {
    //   content.innerHTML = `<div class="leadTips" id="tipsDeviceID${ de.id }">
    //     <div class="tip-box current-value ${color}">
    //       ${ stateStr || valusStr }
    //     </div>
    //   </div>`;
    // } else {
    //   content.innerHTML = `<div class="leadTips" id="tipsDeviceID${ de.id }">
    //     <div class="tip-box current-value ${color}">
    //       ${ valusStr }
    //       ${ stateStr }
    //     </div>
    //   </div>`;
    //   // content.innerHTML = `<div class="leadTips" id="tipsDeviceID${ de.id }">
    //   //   <div class="tip-box current-value ${color}">
    //   //     <div class="device-name">${ de.name }</div>
    //   //     ${ valusStr }
    //   //     ${ stateStr }
    //   //   </div>
    //   // </div>`;
    // }
    config.content = content;
    config.viewer = BIMRat.viewer3D;
    config.objectId = de.e_elementid;
    config.worldPosition = position;
    let customItem = new Glodon.Bimface.Plugins.Drawable.CustomItem(config);
    customItem.onClick(function (e) {
      handleDevice(de);
    });
    BIMRat.drawableContainer.addItem(customItem);
  });
  // BIMRat.viewer3D.setCameraStatus(unitView.camera);
}
function checkStatus(array) {
  const statuses = ['掉线', '故障', '运行', '停止', '开到位', '关到位'];
  for (const status of statuses) {
    if (array.find(item => item.value === status)) {
      return status;
    }
  }
  return ''; // 如果没有匹配的状态
}

function handleDevice(device) {
  Resd.action = true;
  if (device._selected) {
    return;
  }
  const unit = selectSomeDevice(device);
  getUnitView(unit, true);
  showDeviceDetail(device);
}
function selectSomeDevice(device) {
  const unit = Resd.basicUDS.find(item => item._selected);
  if (!unit.deChildren.find(i => i._selected)) {
    BIMRat.viewer3D.setCameraStatus(unitViews[unit.code].camera);
  }
  unit.deChildren.forEach(item => item._selected = item.id === device.id);
  return unit;
}

/* 详情弹出框 */
const detail = reactive({
  device: null,
  dom: null,
  bgModal: 'modal-state-value',
  stateList: [],
  valueList: [],
  active_value: 0,
});
function showDeviceDetail(device) {
  detail.active_value = 0;
  const { e_sensors } = device;
  detail.stateList = e_sensors?.filter(i => i.datatype === '状态型') || [];
  detail.valueList = e_sensors?.filter(i => i.datatype === '数值型') || [];
  if (detail.stateList.length && detail.valueList.length) {
    detail.bgModal = 'modal-state-value';
  } else if (detail.stateList.length) {
    detail.bgModal = 'modal-state';
  } else {
    detail.bgModal = 'modal-value';
  }
  detail.device = device;
  detail.dom = document.getElementById(`tipsDeviceID${ device.id }`);
}
function closeDetail() {
  const unit = Resd.basicUDS.find(item => item.id === detail.device.unit);
  getUnitView(unit);
  detail.device = null;
  detail.dom = null;
  detail.active_value = 0;
}

/* 显示右侧窗口 */
const right = reactive({
  data: null,
  deviceList: [],
  device: null,
});
function setRightData(unit) {
  if (!Resd.ready) {
    return;
  }
  right.data = unit;
  if (unit) {
    right.deviceList = deepCopy(right.data.deChildren);
    analysisDeviceList();
  } else {
    right.deviceList = [];
  }
  right.device = right.deviceList.length ? right.deviceList[0] : null;
}
function analysisDeviceList() {
  right.deviceList.forEach(item => {
    const states = item.e_sensors.filter(i => i.datatype === '状态型');
    const values = item.e_sensors.filter(i => i.datatype === '数值型');
    const state = checkStatus(states || []);
    item.tp_values = values.length ? values[0] : {};
    item.tp_state = state;
  });
}
</script>

<template>
  <div class="left">
    <div class="title" @click="listTitleClick()"> <span>单体列表</span> </div>
    <div class="uContainer">
      <div class="ulistbox scroller">
        <div class="unitBox" v-for="unit in Resd.basicUDS">
          <div class="unitLine" :class="{'isActive': unit._selected}" @click="handleUnit(unit)">
            <img
              :style="{opacity: unit._selected ? 1 : 0.6}"
              :src="require('../assets/device/nameIcon.png')"
            />
            <span>{{ unit.name }}</span>
          </div>
          <template v-if="unit._opened">
            <div
              class="deviceLine"
              :class="{'isActive': device._selected}"
              v-for="device in unit.deChildren"
              @click="handleDevice(device);setRightData(null);"
            >
              <img
                :style="{opacity: device._selected && unit._selected ? 1 : 0.6}"
                :src="require('../assets/device/nameIcon.png')"
              />
              {{ device.name?.replace(`${ unit.name }`, '') }}
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
  
  <div class="right" v-if="right.data">
    <label class="unit-name">{{ right.data.name }}</label>
    
    <div class="value-echarts-box">
      <device-echarts
        v-if="right.device?.tp_values?.id"
        :name="right.device.tp_values.name?.replace(`${ right.device.name }`, '')"
        :sensor="right.device.tp_values.id"
      />
    </div>
    
    <div class="devicelist-header">
      <span>设备名称</span>
      <span>实时值</span>
    </div>
    <div class="devicelist-box scroller">
      <div
        v-for="item in right.deviceList"
        class="device-item"
        :class="{'isActive': item.id === right.device?.id }"
        @click="right.device = item"
      >
        <label>{{ item.name }}</label>
        <template v-if="item.tp_state">
          <div
            v-if="['运行', '停止', '故障'].includes(item.tp_state)"
            class="state-lastdata"
            :class="{'运行': 'green', '停止': 'blue', '故障': 'red'}[item.tp_state]"
          >
            {{ item.tp_state }}
          </div>
          <div class="state-lastdata" v-else>{{ item.tp_state }}</div>
        </template>
        <template v-else-if="item.tp_values">
          <div class="state-lastdata">
            <span>{{ item.tp_values.value }}</span>
            <span class="lastdata-unit" v-if="item.tp_values.unit">{{ item.tp_values.unit }}</span>
          </div>
        </template>
      </div>
    </div>
  </div>
  
  <teleport :to="detail.dom" :disabled="false" v-if="detail.device && detail.dom">
    <div class="detail-container" :class="detail.bgModal">
      <div class="close flex-center-center" @click="closeDetail()">
        <el-icon size="16" color="#84D9D0"><CloseBold /></el-icon>
      </div>
      <div class="header">
        <div class="double-arrow"></div>
        <label>{{ detail.device.name }}</label>
      </div>
      <div class="data-box">
        <template v-if="detail.stateList.length">
          <div class="state-box" :class="detail.valueList.length ? 'model2' : 'model1'">
            <div class="state-item" v-for="item in detail.stateList">
              <span>{{ item.name?.replace(`${ detail.device.name }`, '') }}</span>
              <div
                v-if="['运行', '停止', '故障'].includes(item.value)"
                class="state-lastdata"
                :class="{'运行': 'green', '停止': 'blue', '故障': 'red'}[item.value]"
              >
                {{ item.value }}
              </div>
              <div class="state-lastdata" v-else>{{ item.value }}</div>
            </div>
            <div class="state-item" v-for="item in detail.valueList">
              <span>{{ item.name?.replace(`${ detail.device.name }`, '') }}</span>
              <div class="state-lastdata">
                <span>{{ item.value }}</span>
                <span class="lastdata-unit" v-if="item.unit">{{ item.unit }}</span>
              </div>
            </div>
          </div>
        </template>
        <template v-if="detail.stateList.length && detail.valueList.length">
          <div class="mid-line"></div>
        </template>
        <template v-if="detail.valueList.length">
          <div class="value-box">
            <div class="btns-tab" v-if="detail.valueList.length > 1">
              <button
                v-for="(item, index) in detail.valueList"
                :class="{'isActive': detail.active_value === index}"
                @click="detail.active_value = index"
              >
                {{ item.name?.replace(`${ detail.device.name }`, '') }}
              </button>
            </div>
            <div class="echarts-box" v-if="detail.device">
              <device-echarts
                :name="detail.valueList[detail.active_value].name?.replace(`${ detail.device.name }`, '')"
                :sensor="detail.valueList[detail.active_value].id"
              />
            </div>
          </div>
        </template>
      </div>
    </div>
  </teleport>
</template>

<style lang="scss" scoped>
@font-face {
  font-family: "YouSheBiaoTiHei";
  src: url("/font/优设标题黑.ttf");
}
@keyframes lEnter {
  0% {
    transform: translateX(-450px);
    opacity: 0;
  }
  100% {
    transform: translateX(0px);
    opacity: 1;
  }
}
@supports (scrollbar-width: auto) {
  .scroller {
    scrollbar-width: none;
    -ms-overflow-style: none;
    // scrollbar-width: thin;
    // scrollbar-color: rgba(16, 255, 245, 0.2) #003B44 !important;
  }
}
@supports selector(::-webkit-scrollbar) {
  .scroller::-webkit-scrollbar {
    display: none !important;
  	// width: 1px !important;
  	// border-radius: 1px !important;
  }
  .scroller::-webkit-scrollbar-thumb {
  	// background-color: rgba(16, 255, 249, 0.6) !important;
  	// border-radius: 1px !important;
  }
}
.left {
  position: absolute;
  top: 0;
  left: 0;
  width: 280px;
  height: 100%;
  padding-top: 38px;
  padding-left: 24px;
  background: linear-gradient( 270deg, rgba(13,45,45,0) 0%, rgba(34,41,41,0.8) 100%);
  display: flex;
  flex-direction: column;
  animation: lEnter 1s linear 0s;
  -webkit-animation: lEnter 1s linear 0s;
  animation-fill-mode: backwards;
  -webkit-animation-fill-mode: backwards;
  .title {
    position: relative;
    margin-left: 11px;
    width: fit-content;
    display: flex;
    align-items: center;
    cursor: pointer;
    &::after {
      content: ' ';
      width: 120%;
      height: 2px;
      position: absolute;
      background-color: #10FFF9;
      opacity: 0.6;
      left: 0;
      bottom: 0;
    }
    span {
      font-family: YouSheBiaoTiHei;
      font-size: 20px;
      color: #10FFF9;
      letter-spacing: 1px;
    }
  }
  .uContainer {
    background: linear-gradient( 270deg, rgba(13,45,45,0) 0%, rgba(13,45,45,0.5) 100%);
    border-radius: 2px;
    border: 1px solid;
    border-image: linear-gradient(90deg, rgba(60, 98, 98, 1), rgba(60, 98, 98, 0)) 1 1;
    border-right: none;
    border-left: none;
    width: fit-content;
    max-height: 80%;
    position: relative;
    padding: 15px 0;
  }
  .ulistbox {
    min-width: 210px;
    height: 100%;
    overflow-x: hidden;
    overflow: auto;
    .unitBox:nth-child(1) {
      margin-top: 0;
    }
  }
  .unitBox {
    display: flex;
    flex-direction: column;
    margin-top: 12px;
    img {
      margin: 0 8px;
      width: 16px;
      height: 16px;
    }
    .unitLine {
      display: flex;
      align-items: center;
      font-size: 14px;
      color: #ffffff;
      cursor: pointer;
    }
    .deviceLine {
      margin-top: 12px;
      margin-left: 30px;
      display: flex;
      align-items: center;
      font-size: 14px;
      color: #ffffff;
      cursor: pointer;
    }
    .isActive {
      color: #10FFF9;
    }
  }
}
.right {
  position: absolute;
  top: 40px;
  right: 27px;
  width: 400px;
  height: 780px;
  padding: 33px 12px;
  background: url('../assets/device/right_bg.png') no-repeat center;
  background-size: 100% 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  .unit-name {
    font-family: YouSheBiaoTiHei, YouSheBiaoTiHei;
    font-weight: 400;
    font-size: 24px;
    color: #83B3B7;
    line-height: 28px;
  }
  .value-echarts-box {
    margin-top: 24px;
    width: 100%;
    height: 210px;
  }
  .devicelist-header {
    margin-top: 36px;
    width: 100%;
    height: 36px;
    background: linear-gradient( 180deg, rgba(9,75,72,0.1) 0%, #0B4A47 47%, #15837D 100%);
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 18px;
    font-weight: 500;
    font-size: 14px;
    color: #A2D0D4;
  }
  .devicelist-box {
    flex: 1;
    width: 100%;
    overflow-x: hidden;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
  }
  .device-item {
    margin-top: 8px;
    height: 36px;
    background: linear-gradient( 90deg, rgba(13,45,45,0) 0%, rgba(13,45,45,0.6) 50%, rgba(13,45,45,0) 100%);
    border: 1px solid;
    border-image: linear-gradient(90deg, rgba(51, 156, 163, 0), rgba(51, 156, 163, 1), rgba(51, 156, 163, 0)) 1 1;
    display: flex;
    align-items: center;
    padding: 0 18px;
    cursor: pointer;
    &.isActive {
      background: linear-gradient( 90deg, rgba(18,113,113,0) 0%, rgba(18,113,113,0.8) 50%, rgba(18,113,113,0) 100%);
      border-image: linear-gradient(90deg, rgba(72, 226, 237, 0), rgba(72, 226, 237, 1), rgba(72, 226, 237, 0)) 1 1;
    }
    label {
      font-weight: 400;
      font-size: 14px;
      color: #B2EDE9;
      line-height: 16px;
    }
    .state-lastdata {
      margin-left: auto;
    }
  }
}

/* 设备详情 */
.detail-container {
  position: absolute;
  bottom: 0;
  left: 0;
  transform: translate(-50%, -10px);
  display: flex;
  flex-direction: column;
  &.modal-state-value {
    width: 570px;
    height: 230px;
    background: url('../assets/device/detail_bg_state_value.png') no-repeat center;
    background-size: 100% 100%;
  }
  &.modal-state {
    width: 238px;
    height: 166px;
    background: url('../assets/device/detail_bg_state.png') no-repeat center;
    background-size: 100% 100%;
  }
  &.modal-value {
    width: 342px;
    height: 230px;
    background: url('../assets/device/detail_bg_value.png') no-repeat center;
    background-size: 100% 100%;
  }
  .close {
    position: absolute;
    right: 20px;
    top: 25px;
    transform: translate(50%, -50%);
    width: 25px;
    height: 25px;
    cursor: pointer;
  }
  .header {
    display: flex;
    align-items: center;
    height: 33px;
    padding: 0 12px;
    .double-arrow {
      position: relative;
      height: 13px;
      margin-right: 22px;
      &::before,
      &::after {
        content: '';
        position: absolute;
        width: 0;
        height: 0;
        border-width: 7px 0 7px 6px;
        border-style: solid;
        border-color: transparent transparent transparent #A6FEFE;
        top: 0;
      }
      &::before {
        opacity: 0.4;
        left: 0;
      }
      &::after {
        left: 5px;
      }
    }
    label {
      font-family: YouSheBiaoTiHei;
      font-weight: 400;
      font-size: 16px;
      color: #E5FDFF;
      line-height: 19px;
    }
  }
}
.data-box {
  flex: 1;
  overflow: hidden;
  display: flex;
  align-items: center;
  position: relative;
}
.state-box {
  height: 100%;
  display: flex;
  flex-direction: column;
  &.model1 {
    width: 100%;
    padding: 0 16px;
    justify-content: center;
  }
  &.model2 {
    width: 33%;
    justify-content: flex-start;
    padding: 16px;
  }
  .state-item {
    width: 100%;
    height: 20px;
    margin: 7px 0;
    font-weight: 400;
    font-size: 14px;
    color: #A9D8D8;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
.state-lastdata {
  font-family: YouSheBiaoTiHei;
  font-weight: 400;
  font-size: 20px;
  position: relative;
  color: #E5E8E8;
  &::before {
    position: absolute;
    content: '';
    left: -25px;
    top: 50%;
    transform: translateY(-50%);
    width: 16px;
    height: 16px;
  }
  @mixin state-common-styles($color, $value-bg) {
    color: $color;
    $--before-bg: '../assets/device/' + $value-bg + '.png';
    &::before {
      background: url($--before-bg) no-repeat center;
      background-size: 100% 100%;
    }
  }
  &.green {
    @include state-common-styles(#00FF23, 'state_green');
  }
  &.blue {
    @include state-common-styles(#00FFFC, 'state_blue');
  }
  &.red {
    @include state-common-styles(#FF0000, 'state_red');
  }
  .lastdata-unit {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #A9D8D8;
    margin-left: 9px;
  }
}
.mid-line {
  width: 2px;
  height: 146px;
  margin: 0 16px;
  background: linear-gradient( 180deg, rgba(86,211,219,0) 0%, #56D3DB 49%, rgba(86,211,219,0) 100%);
}
.value-box {
  flex: 1;
  height: 100%;
  padding: 12px 16px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .btns-tab {
    display: flex;
    height: 20px;
    width: fit-content;
    margin-bottom: 10px;
    button {
      background: linear-gradient( 180deg, rgba(3,95,102,0.6) 0%, rgba(3,95,102,0) 100%);
      border: 1px solid #10FFF9;
      font-weight: 500;
      font-size: 12px;
      color: #D3F2EE;
      line-height: 14px;
      cursor: pointer;
      &.isActive {
        background: linear-gradient( 180deg, rgba(16,255,249,0.6) 0%, rgba(3,95,102,0) 100%);
        border: 1px solid #10FFF9;
      }
    }
  }
  .echarts-box {
    flex: 1;
    overflow: hidden;
  }
}
</style>